package com.cn.tutorialjava.demos.web;

import com.cn.tutorialjava.demos.web.utils.GzipUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 启动数据压缩的方式
 */
@RequestMapping("/compress")
@RestController
public class CompressController {
    @GetMapping("/huge-map-stream")
    public ResponseEntity<StreamingResponseBody> getHugeGeoJsonStream() {
        StreamingResponseBody stream = outputStream -> {
            try (GZIPOutputStream gzipOS = new GZIPOutputStream(outputStream);
                 InputStream in = new FileInputStream("E:\\IdeaProjects\\tutorial\\tutorial-java\\src\\main\\resources\\data\\data.json")) {
                byte[] buffer = new byte[8192];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    gzipOS.write(buffer, 0, len);
                }
            }
        };

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Encoding", "gzip");
        headers.setContentType(MediaType.valueOf("application/geo+json"));
        return new ResponseEntity<>(stream, headers, HttpStatus.OK);
    }

}
